import json
import os

from conf.settings import USER_DIR
from db.models import User


def read(username):
    """读取数据"""
    user_file = os.path.join(USER_DIR, f'{username}.json')
    with open(user_file, 'r', encoding='utf8') as f:
        try:
            user_dict = json.load(f)
        except Exception as e:  # 文件为空异常捕获
            return None
    return User.dict2obj(user_dict)


def save(obj):
    """保存数据"""
    user_file = os.path.join(USER_DIR, f'{obj.username}.json')
    with open(user_file, 'w', encoding='utf8') as f:
        json.dump(obj.obj2dict(), f, indent=1, ensure_ascii=False)
